<?php
/***********************************************************
 * 分类模型
 * @作者 pcfcms <1131680521@qq.com>
 * @版权 广州市春风科技有限公司
 * @主页 http://www.pcfcms.com
 * @时间 2019年12月21日
***********************************************************/
namespace app\common\model;
use think\Model;
use think\facade\Db;
use think\facade\Cache;
use app\admin\model\Single;
use app\admin\model\Archives;

class Arctype extends Model
{
    // 初始化
    protected function initialize()
    {
        parent::initialize();
    }

    // 获取单条记录 小潘 by 2020.03.23
    public function getInfo($id, $field = '', $get_parent = false)
    {
        if (empty($field)) {$field = 'c.*, a.*';}
        $field .= ', a.id as typeid';
        // 当前栏目信息
        $result = Db::name('Arctype')->field($field)
            ->alias('a')
            ->where('a.id', $id)
            ->join('channel_type c', 'c.id = a.current_channel', 'LEFT')
            ->cache(true,PCFCMS_CACHE_TIME,"arctype")
            ->find();

        if (!empty($result)) {
            if ($get_parent) {
                $result['typeurl'] = $this->getTypeUrl($result); // 当前栏目的URL
                // 获取当前栏目父级栏目信息
                if ($result['parent_id'] > 0) {
                    $parent_row = Db::name('Arctype')->field($field)
                        ->alias('a')
                        ->where('a.id', $result['parent_id'])
                        ->join('channel_type c', 'c.id = a.current_channel', 'LEFT')
                        ->cache(true,PCFCMS_CACHE_TIME,"arctype")
                        ->find();
                    $ptypeurl = $this->getTypeUrl($parent_row);
                    $parent_row['typeurl'] = $ptypeurl;
                } else {
                    $parent_row = $result;
                }
                // 给每个父类字段开头加上p
                foreach ($parent_row as $key => $val) {
                    $newK = 'p'.$key;
                    $parent_row[$newK] = $val;
                }
                $result = array_merge($result, $parent_row);
            } else {
                $result = $this->parentAndTopInfo($id, $result);
            }
        }
        return $result;
    }

    // 获取指定栏目的父级和顶级栏目信息（用于前台与静态生成） 小潘 by 2020.03.23
    public function parentAndTopInfo($id, $result = [])
    {
        $result['typeurl'] = $this->getTypeUrl($result); // 当前栏目的URL
        if (!empty($result['parent_id'])) {
            // 当前栏目的父级栏目信息
            $parent_row = Db::name('arctype')->where('id', $result['parent_id'])
                ->cache(true,PCFCMS_CACHE_TIME,"arctype")
                ->find();
            $ptypeid = $parent_row['id'];
            $ptypeurl = $this->getTypeUrl($parent_row);
            $ptypename = $parent_row['typename'];
            $pdirname = $parent_row['dirname'];
            // 当前栏目的顶级栏目信息
            if (!isset($result['toptypeurl'])) {
                $allPid = $this->getAllPid($id);
                $toptypeinfo = current($allPid);
                $toptypeid = $toptypeinfo['id'];
                $toptypeurl = $this->getTypeUrl($toptypeinfo);
                $toptypename = $toptypeinfo['typename'];
                $topdirname = $toptypeinfo['dirname'];
            }
        } else {
            // 当前栏目的父级栏目信息 或 顶级栏目的信息
            $toptypeid = $ptypeid = $result['id'];
            $toptypeurl = $ptypeurl = $result['typeurl'];
            $toptypename = $ptypename = $result['typename'];
            $topdirname = $pdirname = $result['dirname'];
        }
        // 当前栏目的父级栏目信息
        $result['ptypeid'] = $ptypeid;
        $result['ptypeurl'] = $ptypeurl;
        $result['ptypename'] = $ptypename;
        $result['pdirname'] = $pdirname;
        // 当前栏目的顶级栏目信息
        !isset($result['toptypeid']) && $result['toptypeid'] = $toptypeid;
        !isset($result['toptypeurl']) && $result['toptypeurl'] = $toptypeurl;
        !isset($result['toptypename']) && $result['toptypename'] = $toptypename;
        !isset($result['topdirname']) && $result['topdirname'] = $topdirname;
        return $result;
    }

    // 获取当前栏目的所有父级 小潘 by 2020.03.23
    public function getAllPid($id)
    {
        $cacheKey = array('common','model','Arctype','getAllPid',$id,);
        $cacheKey = json_encode($cacheKey);
        $data = cache::get($cacheKey);
        if (empty($data)) {
            $data = array();
            $map = [];
            $map[] = ['status','=',1];
            $map[] = ['is_del','=',0];
            $typeid = $id;
            $arctype_list = DB::name('Arctype')->field('*, id as typeid')->where($map)->select()->toArray();
            $arctype_list = array_combine(array_column($arctype_list, 'id'), $arctype_list);
            if (isset($arctype_list[$typeid])) {
                // 第一个先装起来
                $arctype_list[$typeid]['typeurl'] = $this->getTypeUrl($arctype_list[$typeid]);
                $data[$typeid] = $arctype_list[$typeid];
            } else {
                return $data;
            }
            while (true)
            {
                $typeid = $arctype_list[$typeid]['parent_id'];
                if($typeid > 0){
                    if (isset($arctype_list[$typeid])) {
                        $arctype_list[$typeid]['typeurl'] = $this->getTypeUrl($arctype_list[$typeid]);
                        $data[$typeid] = $arctype_list[$typeid];
                    }
                } else {
                    break;
                }
            }
            $data = array_reverse($data, true);
            Cache::tag('arctype')->set($cacheKey, $data);
        }
        return $data;
    }

    // 获取栏目的URL 小潘 by 2020.03.23
    public function getTypeUrl($res)
    {
        if ($res['is_part'] == 1) {
            $typeurl = $res['typelink'];
        } else {
            $ctl_name = get_controller_byct($res['current_channel']);
            $typeurl = typeurl("{$ctl_name}/lists", $res);
        }
        return $typeurl;
    }

    // 检测是否有子栏目 小潘 by 2020.03.04
    public function hasChildren($id)
    {
        if (is_array($id)) {
            $ids = array_unique($id);
            $row = Db::name('arctype')
                ->field('parent_id, count(id) AS total')
                ->where('parent_id','IN', $ids)
                ->group('parent_id')
                ->select()->toArray();
            return $row;
        } else {
            $count = Db::name('arctype')->where('parent_id', $id)->count('id');
            return ($count > 0 ? 1 : 0);
        }
    }

    // 新增栏目数据 
    // 小潘 by 2020.03.04
    public function addData($data = [])
    {
        $insertId = false;
        if (!empty($data)) {
            unset($data['file']);
            $insertId = Db::name('arctype')->insertGetId($data);
            if($insertId){
                if ($data['current_channel'] == 6) {
                    $archivesData = array(
                        'title' => $data['typename'],
                        'typeid' => $insertId,
                        'channel' => $data['current_channel'],
                        'admin_id' => $data['admin_id'],
                        'seo_description' => '',
                        'sort_order' => 100,
                        'add_time' => getTime(),
                    );
                    $aid = Db::name('archives')->insertGetId($archivesData);
                    if ($aid) {
                        if (!isset($post['addonFieldExt'])) {
                            $post['addonFieldExt'] = array(
                                'typeid' => $archivesData['typeid'],
                            );
                        } else {
                            $post['addonFieldExt']['typeid'] = $archivesData['typeid'];
                        }
                        !isset($post['addonFieldExt']['content']) && $post['addonFieldExt']['content'] = '';
                        $addData = array(
                            'addonFieldExt' => $post['addonFieldExt'],
                        );
                        $addData = array_merge($addData, $archivesData);
                        $Single = new Single();
                        $Single->afterSave($aid, $addData, 'add');
                    }
                }
            }
        }
        return $insertId;
    }

    //编辑栏目数据 
    public function pcfupdateData($data = [])
    {
        $pbool = false; 
        if (!empty($data)) {
            $pbool = Db::name('arctype')->where('id', $data['id'])->update($data);
            if($pbool){
                // 批量更新所有子孙栏目的最顶级模型ID
                $allSonTypeidArr = $this->getHasChildren($data['id'], false); // 获取当前栏目的所有子孙栏目（不包含当前栏目）
                if (!empty($allSonTypeidArr)) {
                    $i = 1;
                    $minuendGrade = 0;
                    foreach ($allSonTypeidArr as $key => $val) {
                        if ($i == 1) {
                            $firstGrade = intval($data['grade']);
                            $minuendGrade = intval($data['grade']) - $firstGrade;
                        }
                        $update_data = array(
                            'channeltype' => $data['channeltype'],
                            'update_time' => getTime(),
                            'grade'   => Db::raw('grade+'.$minuendGrade),
                        );
                        Db::name('arctype')->where('id', $val['id'])->update($update_data);
                        ++$i;
                    }
                }
                // 存储单页模型
                if ($data['current_channel'] == 6) {
                    $archivesData = array(
                        'title' => $data['typename'],
                        'typeid'=> $data['id'],
                        'channel'   => $data['current_channel'],
                        'seo_description'   => '',
                        'sort_order'   => 100,
                        'update_time'  => getTime(),
                    );
                    $aid = Db::name('single_content')->where('typeid',$data['id'])->value('aid');
                    if (empty($aid)) {
                        $opt = 'add';
                        $archivesData['add_time'] = getTime();
                        $up = $aid = Db::name('archives')->insertGetId($archivesData);
                    } else {
                        $opt = 'edit';
                        $up = Db::name('archives')->where('aid',$aid)->update($archivesData);
                    }
                    if ($up) {
                        if (!isset($post['addonFieldExt'])) {
                            $post['addonFieldExt'] = array('typeid' => $data['id']);
                        } else {
                            $post['addonFieldExt']['typeid'] = $data['id'];
                        }
                        if(isset($post['addonFieldExt']['content']) && empty($post['addonFieldExt']['content'])){
                            $post['addonFieldExt']['content'] = '';
                        }
                        $updateData = array(
                            'addonFieldExt' => $post['addonFieldExt'],
                        );
                        $updateData = array_merge($updateData, $archivesData);
                        $Single = new Single();
                        $Single->afterSave($aid, $updateData, $opt);
                    }
                }
            }
        }
        return $pbool;
    }

    // 伪删除指定栏目（包括子栏目、所有相关文档）
    public function pseudo_del($typeid)
    {
        $where = [];
        $childrenList = $this->getHasChildren($typeid); // 获取当前栏目以及所有子栏目
        $typeidArr = get_arr_column($childrenList, 'id'); // 获取栏目数组里的所有栏目ID作为新的数组
        $typeidArr2 = $typeidArr;
        $where[] = ['is_del','=',0];
        $where[] = ['del_method','=',0];
        // 标记当前栏目以及子栏目为被动伪删除
        $sta1 = Db::name('arctype')
            ->where($where)
            ->where('id','IN',$typeidArr)
            ->cache(true,null,"arctype")
            ->update([
                'is_del' => 1,
                'del_method' => 2, // 1为主动删除，2为跟随上级栏目被动删除
                'update_time' => getTime(),
            ]); 

        // 标记当前栏目为主动伪删除
        $sta2 = Db::name('arctype')
            ->where('id','IN',$typeidArr2)
            ->cache(true,null,"arctype")
            ->update([
                'is_del'    => 1,
                'del_method'    => 1, // 1为主动删除，2为跟随上级栏目被动删除
                'update_time'   => getTime(),
            ]);
        if ($sta1 && $sta2) {
            $Archives = new Archives();
            $Archives->pseudo_del($typeidArr); // 删除文档
            return true;
        }
        return false;
    }

    // 获取当前栏目及所有子栏目 
    // 小潘 by 2020.03.04
    public function getHasChildren($id, $self = true)
    {
        $cacheKey = "common_model_Arctype_getHasChildren_{$id}_{$self}";
        $result = cache::get($cacheKey);
        if (empty($result)) {
            $where =[];
            $where[] = ['status','=',1];
            $where[] = ['is_del','=',0];
            $res = Db::name('arctype')->where($where)->order('parent_id asc, sort_order asc')->select()->toArray();
            foreach ($res as $key => $value) {
                $res[$key]['has_children'] = DB::name('arctype')->where('parent_id',$value['id'])->count('id');
            }
            $result = arctype_options($id, $res, 'id', 'parent_id');
            if (!$self) {
                array_shift($result);
            }
            Cache::tag('arctype')->set($cacheKey, $result);
        }
        return $result;
    }

    // 每个栏目的顶级栏目的目录名称
    public function getEveryTopDirnameList()
    {
        $result = cache::get('common_getEveryTopDirnameList_model');
        if ($result === false){
            $fields = "c.id, c.parent_id, c.dirname, c.grade, count(s.id) as has_children";
            $row = Db::name('arctype')
                ->field($fields)
                ->alias('c')
                ->join('arctype s','s.parent_id = c.id','LEFT')
                ->group('c.id')
                ->order('c.parent_id asc, c.sort_order asc, c.id')
                ->cache(true,PCFCMS_CACHE_TIME,"arctype")
                ->select()->toArray();
            $row = arctype_options(0, $row, 'id', 'parent_id');
            $result = array();
            foreach ($row as $key => $val) {
                if (empty($val['parent_id'])) {
                    $val['tdirname'] = $val['dirname'];
                } else {
                    $val['tdirname'] = isset($row[$val['parent_id']]['tdirname']) ? $row[$val['parent_id']]['tdirname'] : $val['dirname'];
                }
                $row[$key] = $val;
                $result[md5($val['dirname'])] = $val;
            }
            cache::set('common_getEveryTopDirnameList_model', $result);
        }
        return $result;
    }

}